﻿#ifndef XQTHREADMAP_H
#define XQTHREADMAP_H
#include<atomic>
#include<QReadWriteLock>
#include<QMap>
//线程安全map
template<typename Key,typename T>
class XQThreadMap
{
public:
	void insert(const Key& key, const T& value);//插入
public:
	auto find(const Key& key);
	template <typename It>
	auto erase(It it);
	auto begin();
	auto end();
	auto key(const T& value);
	auto keys();
	auto values();
public:
	void remove(const Key& key);
	template <typename _Pr1>
	void remove_if(_Pr1 _Pred);
public:
	size_t size();
	bool isEmpty();
	void clear();
public:
	
public:
	QReadWriteLock& lock();//返回内部读写锁
	QMap<Key, T>& map();//返回内部链表
protected:
	QReadWriteLock m_lock;
	QMap<Key,T> m_map;
};
template<typename Key,typename T>
inline void XQThreadMap<Key,T>::insert(const Key& key, const T& value)
{
	QWriteLocker locker(&m_lock);
	m_map[key]=value;
}

template<typename Key,typename T>
inline auto XQThreadMap<Key,T>::find(const Key& key)
{
	QReadLocker locker(&m_lock);
	auto it=m_map.find(key);
	/*if (it == m_map.end())
		return T();*/
	return it;
}

template<typename Key,typename T>
inline auto XQThreadMap<Key,T>::begin()
{
	QReadLocker locker(&m_lock);
	return m_map.begin();
}

template<typename Key,typename T>
inline auto XQThreadMap<Key,T>::end()
{
	QReadLocker locker(&m_lock);
	return m_map.end();
}
template<typename Key, typename T>
inline auto XQThreadMap<Key, T>::key(const T& value)
{
	QReadLocker locker(&m_lock);
	return m_map.key(value);
}
template<typename Key, typename T>
inline auto XQThreadMap<Key, T>::keys()
{
	QReadLocker locker(&m_lock);
	return m_map.keys();
}
template<typename Key, typename T>
inline auto XQThreadMap<Key, T>::values()
{
	QReadLocker locker(&m_lock);
	return m_map.values();
}
template<typename Key,typename T>
inline void XQThreadMap<Key,T>::remove(const Key& key)
{
	QWriteLocker locker(&m_lock);
	m_map.remove(key);
}

template<typename Key,typename T>
inline size_t XQThreadMap<Key,T>::size()
{
	QReadLocker locker(&m_lock);
	return m_map.size();
}

template<typename Key,typename T>
inline bool XQThreadMap<Key,T>::isEmpty()
{
	QReadLocker locker(&m_lock);
	return m_map.isEmpty();
}

template<typename Key,typename T>
inline void XQThreadMap<Key,T>::clear()
{
	QWriteLocker locker(&m_lock);
	m_map.clear();
}

template<typename Key,typename T>
inline QReadWriteLock& XQThreadMap<Key,T>::lock()
{
	return m_lock;
}

template<typename Key,typename T>
inline QMap<Key, T>& XQThreadMap<Key,T>::map()
{
	return m_map;
}

template<typename Key,typename T>
template<typename It>
inline auto XQThreadMap<Key,T>::erase(It it)
{
	QWriteLocker locker(&m_lock);
	return m_map.erase(it);
}

template<typename Key,typename T>
template<typename _Pr1>
inline void XQThreadMap<Key,T>::remove_if(_Pr1 _Pred)
{
	QWriteLocker locker(&m_lock);
	std::remove_if(m_map.begin(), m_map.end(), _Pred);
}
#endif